package com.frog.framework.ms.api.dto;

import java.beans.Transient;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页返回结果模板
 * @author wuqiong 2022/2/28
 */
public class Page<T> implements Serializable {

    private static final long serialVersionUID = 7963949513138399437L;
    /**
     * 当前页码
     */
    private int pageNum;

    /**
     * 当前页数据条数
     */
    private int pageSize;

    /**
     * 总页数
     */
    private int totalPage;

    /**
     * 总条数
     */
    private long totalCount;

    /**
     * 数据集合
     */
    private List<T> data;

    public static <T> Page<T> create(int page, int pageSize, long totalCount) {
        return create(page, pageSize, totalCount, null);
    }

    /**
     * 根据参数封装分页信息并返回
     * @param pageNum 当前页码
     * @param pageSize 当前页数据条数
     * @param totalCount 总条数
     * @param data 返回数据集合
     * @return Page<T>
     * @author wuqiong 2022/2/28 17:03
     */
    public static <T> Page<T> create(int pageNum, int pageSize, long totalCount, List<T> data) {
        Page<T> instance = new Page<>();
        instance.setPageNum(Math.max(pageNum, 1));
        instance.setPageSize(pageSize);
        instance.setTotalCount(totalCount);
        instance.setTotalPage((int) Math.ceil((double) totalCount / (double) pageSize));
        instance.setData(data);
        return instance;
    }

    /**
     * 返回一个空分页表
     * @return Page<T>
     * @author wuqiong 2022/2/28 17:03
     */
    public static <T> Page<T> empty() {
        return Page.create(0, 0, 0, new ArrayList<>());
    }

    @Transient
    public int getOffset() {
        return (pageNum - 1) * pageSize;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int page) {
        this.pageNum = Math.max(page, 1);
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = Math.max(pageSize, 1);
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        this.totalCount = totalCount;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }
}
